<template>
  <div>
    <el-dialog :title="title"
               :visible.sync="visible"
               v-loading="loading"
               :before-close="modalClose"
               :close-on-click-modal="false"
               :close-on-press-escape="false"
               width="80%">
      <el-form ref="formRefs"
               :model="formModel"
               :rules="formRules"
               label-width="120px">
        <el-form-item label="合并症名称："
                      prop="name">
          <el-input v-model="formModel.name"
                    placeholder="请输入合并症名称"
                    class="w-200"></el-input>
        </el-form-item>
        <el-form-item label="关联检测项："
                      prop="deviceTargetDto">
          <el-select v-model="detectIds"
                     filterable
                     remote
                     clearable
                     reserve-keyword
                     placeholder="请输入检测项"
                     :remote-method="searchMethod"
                     :loading="loading1"
                     @change="handleSelectItems"
                     class="w-200">
            <el-option v-for="item in optionsFilterList"
                       :key="item.id"
                       :label="item.name"
                       :value="item.id">
            </el-option>
          </el-select>
          <el-button type="primary"
                     @click="handleAddDetect(detectIds)">新 增</el-button>
          <el-card class="mt-20">
            <div slot="header">已选检测项</div>
            <el-table :data="deviceTargetDto"
                      border
                      style="width: 100%">
              <el-table-column prop="deviceName"
                               label="项目名称">
              </el-table-column>
              <el-table-column prop="referenceName"
                               label="检测指标">
              </el-table-column>
              <el-table-column prop="result"
                               label="结果">
                <template slot-scope="scope">
                  <el-select v-model="scope.row.resultArr"
                             placeholder="请选择判断结果"
                             class="w-200"
                             multiple>
                    <el-option v-for="item in scope.row.resultSet"
                               :key="item"
                               :label="item"
                               :value="item"
                               class="w-200">
                    </el-option>
                  </el-select>
                </template>
              </el-table-column>
              <el-table-column prop="condition"
                               label="条件">
                <template slot-scope="scope">
                  <el-select v-model="scope.row.condition"
                             placeholder="请选择条件"
                             class="w-200">
                    <el-option v-for="item in conditionList"
                               :key="item.id"
                               :label="item.name"
                               :value="item.id">
                    </el-option>
                  </el-select>
                </template>
              </el-table-column>
              <el-table-column prop="errorCount"
                               label="异常次数">
                <template slot-scope="scope">
                  <el-input v-model="scope.row.errorCount"
                            placeholder="请输入异常次数"
                            class="w-200"></el-input>
                </template>
              </el-table-column>
              <el-table-column label="删 除"
                               width="120">
                <template slot-scope="scope">
                  <el-button type="danger"
                             @click="delRow(deviceTargetDto, scope.$index, 'detect')">删 除</el-button>
                </template>
              </el-table-column>
            </el-table>

          </el-card>
        </el-form-item>

        <el-form-item label="病症知识点：">
          <div>
            <vue-neditor-wrap :destroy="true"
                              v-model="formModel.knowledgePoints"
                              :config="myConfig"></vue-neditor-wrap>

          </div>
        </el-form-item>
        <el-form-item label="是否需要进一步确认并发症："
                      label-width="240">
          <el-radio-group v-model="formModel.confirmAgain">
            <el-radio :label="0">否</el-radio>
            <el-radio :label="1">是</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="推荐医院检查项目："
                      prop="recommendableProjects"
                      label-width="150px">
          <el-input v-model="formModel.recommendableProjects"
                    placeholder="请输入推荐医院检查项目"
                    class="w-500"></el-input>
        </el-form-item>
        <el-form-item label="推荐健康风险筛查项目："
                      prop="risk"
                      label-width="180px">
          <el-select v-model="riskIds"
                     placeholder="请选择健康风险筛查项目"
                     multiple
                     filterable
                     remote
                     reserve-keyword
                     :remote-method="remoteMethod"
                     :loading="loading1"
                     class="w-200"
                     @change="handleSelect">
            <el-option v-for="item in riskFilterList"
                       :key="item.healthCheckPackageId"
                       :label="item.name"
                       :value="item.healthCheckPackageId">
            </el-option>
          </el-select>
          <el-button type="primary"
                     @click="handleAddRisk(riskIds)">新 增</el-button>
        </el-form-item>
        <el-form-item label="已选健康筛查项目："
                      label-width="180px">
          <el-table :data="formModel.themeHealthDtoList"
                    style="width: 100%"
                    border>
            <el-table-column prop="name"
                             label="健康筛查项目">
            </el-table-column>
            <el-table-column prop="type"
                             label="健康筛查项目类型">
            </el-table-column>
            <el-table-column prop="salesScript"
                             label="销售话术">
              <template slot-scope="scope">
                <el-input v-model="scope.row.salesScript"
                          placeholder="请输入销售导语"
                          class="w-200"></el-input>
              </template>
            </el-table-column>
            <el-table-column prop="option"
                             label="操作"
                             width="150"
                             align="center">
              <template slot-scope="scope">
                <el-button type="danger"
                           @click="delRisk(formModel.themeHealthDtoList, scope.$index)">删 除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-form-item>
        <!-- 推荐器械 -->
        <el-form-item label="推荐器械：">
          <el-button type="primary"
                     @click="handleAdd('equipment')">新 增</el-button>
          <el-table :data="formModel.apparatusRequestDtoList"
                    style="width: 100%"
                    border
                    class="mt-20">
            <el-table-column prop="drugName"
                             label="器械名称">
            </el-table-column>
            <el-table-column prop="logoUrl"
                             label="图片">
              <template slot-scope="scope">
                <el-image style="width: 80px; height: 80px"
                          :src="scope.row.logoUrl"
                          :preview-src-list="[scope.row.logoUrl]">
                </el-image>
              </template>
            </el-table-column>
            <el-table-column prop="salesScript"
                             label="销售导语">
            </el-table-column>
            <el-table-column prop="option"
                             label="操作"
                             width="150"
                             align="center">
              <template slot-scope="scope">
                <el-button type="danger"
                           @click="delRow(formModel.apparatusRequestDtoList, scope.$index, 'equipment')">删 除</el-button>
              </template>
            </el-table-column>
          </el-table>
          <equipment-dialog :equipmentDataObj="equipmentDataObj"
                            @childEquipmentData="childEquipmentData"
                            :equipmentDataList="formModel.apparatusRequestDtoList"
                            :visible.sync="isShowEquipment"
                            v-if="isShowEquipment"></equipment-dialog>
        </el-form-item>
        <!-- 推荐商品 -->
        <el-form-item label="推荐商品：">
          <el-button type="primary"
                     @click="handleAdd('shop')">新 增</el-button>
          <el-table :data="formModel.sellDrugDtoList"
                    style="width: 100%"
                    border
                    class="mt-20">
            <el-table-column prop="drugType"
                             label="商品类别">
              <template slot-scope="scope">
                <el-tag type="success"
                        v-if="scope.row.drugType === 1">中药</el-tag>
                <el-tag type="success"
                        v-if="scope.row.drugType === 2">化学药</el-tag>
                <el-tag type="danger"
                        v-if="scope.row.drugType === 3">中成药</el-tag>
                <el-tag type="info"
                        v-if="scope.row.drugType === 4">保健品</el-tag>
                <el-tag type="warning"
                        v-if="scope.row.drugType === 5">器械</el-tag>
                <el-tag type="success"
                        v-if="scope.row.drugType === 6">健康筛查</el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="drugName"
                             label="商品名称">
            </el-table-column>
            <el-table-column prop="logoUrl"
                             label="图片"
                             width="120"
                             align="center">
              <template slot-scope="scope">
                <el-image style="width: 80px; height: 80px"
                          :src="scope.row.logoUrl"
                          :preview-src-list="[scope.row.logoUrl]">
                </el-image>
              </template>
            </el-table-column>
            <el-table-column prop="standard"
                             label="规格"
                             width="100"
                             align="center">
            </el-table-column>
            <el-table-column prop="drugPackage"
                             label="包装"
                             width="100"
                             align="center">
            </el-table-column>
            <el-table-column prop="functionalIndications"
                             label="功能主治">
            </el-table-column>
            <el-table-column prop="taboo"
                             label="禁忌">
            </el-table-column>
            <el-table-column prop="adverseReaction"
                             label="不良反应">
            </el-table-column>
            <el-table-column prop="salesScript"
                             label="销售话术">
            </el-table-column>
            <el-table-column prop="option"
                             label="操作"
                             width="120"
                             align="center">
              <template slot-scope="scope">
                <el-button type="danger"
                           @click="delRow(formModel.sellDrugDtoList, scope.$index, 'shop')">删 除</el-button>
              </template>
            </el-table-column>
          </el-table>
          <shop-dialog :shopDataObj="shopDataObj"
                       :fileUpload="fileUpload"
                       @childShopData="childShopData"
                       :shopDataList="formModel.sellDrugDtoList"
                       :visible.sync=isShowShop
                       v-if="isShowShop">
          </shop-dialog>
        </el-form-item>
        <!-- 联合荐药 -->
        <el-form-item label="联合荐药：">
          <el-button type="primary"
                     @click="handleAdd('medicine')">新 增</el-button>
          <el-table :data="recommendMedicineRequestDtoList"
                    style="width: 100%"
                    border
                    class="mt-20">
            <el-table-column prop="drugType"
                             label="类别"
                             width="120">
              <template slot-scope="scope">
                <el-tag type="success"
                        v-if="scope.row.drugType === 2">化学药</el-tag>
                <el-tag type="dager"
                        v-if="scope.row.drugType === 3">中成药</el-tag>
                <el-tag type="warning"
                        v-if="scope.row.drugType === 4">保健品</el-tag>
                <el-tag type="info"
                        v-if="scope.row.drugType === 5">器械</el-tag>
                <el-tag type="dager"
                        v-if="scope.row.drugType === 6">健康筛查</el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="value"
                             label="内容">
              <template slot-scope="scope">
                <el-tag type="success"
                        v-for="(item, index) in scope.row.value"
                        :key="index"
                        style="margin-right:5px; margin-bottom:2px;">
                  {{item.drugName}}--{{item.factoryName}} </el-tag>
              </template>
            </el-table-column>
          </el-table>
          <table style="width: 100%"
                 border="0"
                 class="table-cell"
                 cellspacing="0"
                 cellpadding="0">
            <tr>
              <td width="121"
                  class="first-td">
                <el-tag type="danger">健康筛查项目</el-tag>
              </td>
              <td>
                <el-tag v-for="item in formModel.themeHealthDtoList"
                        :key="item.id"
                        type="danger"
                        style="margin-right:5px">
                  {{item.name}}--{{item.type}}
                </el-tag>
              </td>
            </tr>
            <tr>
              <td width="121"
                  class="first-td">
                <el-tag type="info">销售话术</el-tag>
              </td>
              <td>
                {{formModel.recommendSalesScript}}
              </td>
            </tr>
          </table>
          <medicine-dialog :medicineDataObj="medicineDataObj"
                           @childMedicineData="childMedicineData"
                           :visible.sync="isShowMedicine"
                           v-if="isShowMedicine"></medicine-dialog>
        </el-form-item>

      </el-form>
      <p align="center">
        <el-button type="info"
                   @click="modalClose">返 回</el-button>
        <el-button type="primary"
                   @click="submitForm">保 存</el-button>
      </p>
    </el-dialog>
  </div>
</template>
<script>
  import { mapGetters } from 'vuex'
  import VueNeditorWrap from 'vue-neditor-wrap'
  import equipmentDialog from './equipmentDialog' // 推荐器械
  import shopDialog from './shopDialog' // 推荐商品
  import medicineDialog from './medicineDialog' // 联合荐药
  export default {
    name: '', // 合并症管理弹窗
    props: {
      dataObj: {
        type: Object,
        default: {}
      },
      visible: {
        type: Boolean,
        default: false
      },
      getList: {
        type: Function,
        default: null
      },
    },
    data () {
      return {
        myConfig: {
          // 你的UEditor资源存放的路径,相对于打包后的index.html
          UEDITOR_HOME_URL: this.api.uEditorHomeUrl,
          // 编辑器不自动被内容撑高
          autoHeightEnabled: false,
          // 初始容器高度
          initialFrameHeight: '418',
          // 初始容器宽度
          initialFrameWidth: '100%',
          // 关闭自动保存
          enableAutoSave: false,
          scaleEnabled: true
        },
        title: '新 增',
        loading: false,
        loading1: false,
        isShowEquipment: false, // 推荐器械
        isShowShop: false, // 推荐商品
        isShowMedicine: false, // 联合荐药
        formModel: {
          name: '', // 并症名称
          deviceTargetDto: [], // 推荐检测项
          knowledgePoints: '', // 病症知识点
          confirmAgain: 0, // 确认并发症
          recommendableProjects: '', // 推荐医院检查项目
          themeHealthDtoList: [], // 已选健康筛查项目列表
          apparatusRequestDtoList: [], // 推荐器械列表
          sellDrugDtoList: [], // 推荐商品列表
          recommendMedicineRequestDtoList: [], // 联合荐药列表
          recommendSalesScript: '', // 销售话术
          diseaseKnowledge: '', // 销售话术
          healthAdvice: '', // 销售话术
        },
        recommendMedicineRequestDtoList: [],
        deviceTargetDto: [],
        detectIds: '', // 推荐检测项
        formRules: {
          name: [{ required: true, message: '请输入并症名称', trigger: 'blur' }],
          knowledgePoints: [{ required: true, message: '请输入病症知识点', trigger: 'blur' }],
        },
        optionsList: [],
        optionsFilterList: [],
        conditionList: [
          { id: 0, name: '间隔0天' },
          { id: 1, name: '间隔1天' },
        ],
        // 推荐健康风险筛查项目
        riskList: [],
        riskFilterList: [],
        riskIds: [], // 推荐健康风险筛查项目
        equipmentDataObj: {}, // 推荐器械
        shopDataObj: {}, // 推荐商品
        medicineDataObj: {}, // 联合荐药
        tableDetect: [], // 已选检测项
        typeList: [
          { drugType: 2, drugName: "化学药" },
          { drugType: 3, drugName: "中成药" },
          { drugType: 4, drugName: "保健品" },
          { drugType: 5, drugName: "器械" }
        ],
        childMedicineTableData: []
      }
    },
    methods: {
      modalClose () {
        this.$emit('update:visible', false); // 直接修改父组件的属性
      },
      // 搜索联检测项
      searchMethod (query) {
        if (query !== '') {
          let _this = this;
          _this.loading1 = true; // 锁住
          this.post(this.api.promote.getDeviceList, {
            name: query,
            pageIndex: 0,
            pageSize: 10
          }).then(res => {
            if (res.data.code === '200') {
              _this.loading1 = false;
              _this.optionsList = res.data.object;
            }
          })

          /**
           * 搜索内容渲染到下拉框
           * 从 this.optionsList 把数据赋值到 this.optionsFilterList
           * 只有这样才能起作用
           */
          setTimeout(() => {
            _this.loading1 = false;
            _this.optionsFilterList = _this.optionsList.filter(item => item.name.indexOf(query) > -1);
          }, 200);
        } else {
          this.optionsFilterList = [];
        }
      },
      // 增加推推荐检测项
      handleAddDetect (selVal) {
        if (selVal === '') {
          this.$message.error('请选择关联检测项!');
          return
        }

        if (this.deviceTargetDto.some(item => item.deviceId === selVal)) {
          this.$message.error('推荐检测项不能重复添加!');
          this.detectIds = '';
          return
        }
        this.post(this.api.promote.getReferenceInfo, { deviceId: selVal })
          .then(res => {
            if (res.data.code === '200') {
              let resData = res.data.object;
              this.detectIds = '';
              // this.getResult(this.tableData);
              resData.forEach(item => {
                if (item.resultSet.length > 0) {
                  this.deviceTargetDto.push(item);
                }
              })
              if (resData.some(el => el.resultSet.length === 0)) {
                this.$message.error('该检测项目未配置检测结果判断!');
                return;
              }
            }

          })
      },
      // 选中关联检测项
      handleSelectItems (item) {
        this.detectIds = item;
      },
      getResult (data) {
        data.forEach(item => {
          let obj = {};
          // 将数组转化为对象
          for (let key in item.resultSet) {
            obj[key] = item.resultSet[key];
          };
          item.resultSet = Object.keys(obj).map(val => ({
            name: obj[val]
          }));
        })

      },
      // 提交
      submitForm () {

        this.$refs['formRefs'].validate((valid) => {
          if (valid) {
            // if (this.deviceTargetDto.length === 0) {
            //   this.$message.error('请选择关联检测项!');
            //   return
            // }
            this.formModel.deviceTargetDto = this.deviceTargetDto.map(item => ({
              ...item,
              result: JSON.stringify(item.resultArr)
            }));
            // 第一种方式
            /* let falg = this.formModel.deviceTargetDto.every(item => {
              if (item.resultArr.length > 0) {
                return true;
              }
            });
            if (!falg) {
              this.$message.error('请选择判断结果!');
              return
            } */
            // 第二种方式
            if (this.formModel.deviceTargetDto.some(item => item.resultArr.length === 0)) {
              this.$message.error('请选择判断结果!');
              return;
            }
            // 联合荐药
            let recommendMedicine = []
            this.recommendMedicineRequestDtoList.forEach(item => {
              item.value.forEach(list => {
                recommendMedicine.push(list);
              })
            })
            this.formModel.recommendMedicineRequestDtoList = recommendMedicine;
            if (this.dataObj) { // 编辑
              this.post(this.api.promote.updateComplication, this.formModel, { showFullScreenLoading: true }).then(res => {
                if (res.data.code === '200') {
                  this.$message.success('保存成功!');
                  this.modalClose();
                  this.$parent.getList();
                }
              })
            } else { // 新增
              this.post(this.api.promote.saveComplication, this.formModel, { showFullScreenLoading: true }).then(res => {
                if (res.data.code === '200') {
                  this.$message.success('保存成功!');
                  this.modalClose();
                  this.$parent.getList();
                }
              })
            }
          }
        })
      },
      handleAdd (option) {
        switch (option) {
          case 'equipment':
            this.isShowEquipment = true;
            break;
          case 'shop':
            this.isShowShop = true;
            break;
          case 'medicine':
            this.isShowMedicine = true;
            let { recommendSalesScript, recommendMedicineRequestDtoList } = this.formModel;
            let data = this.childMedicineTableData;
            this.medicineDataObj = {
              recommendSalesScript: recommendSalesScript,
              recommendMedicineRequestDtoList: data.length === 0 ? recommendMedicineRequestDtoList : data
            };
            break;
        }
      },
      delRow (table, index, option) {
        table.splice(index, 1);
      },
      // 推荐器械,接收子组件传递过来的数据
      childEquipmentData (data) {
        this.formModel.apparatusRequestDtoList.push(data);
      },
      // 推荐商品,接收子组件传递过来的数据
      childShopData (data) {
        this.formModel.sellDrugDtoList.push(data);
      },
      // 联合荐药,接收子组件传递过来的数据
      childMedicineData (data) {
        this.childMedicineTableData = data.tableData;
        this.formModel.recommendSalesScript = data.recommendSalesScript;
        const result = this.typeList.map(item => ({
          ...item,
          value: data.tableData.filter(sItem => item.drugType === sItem.drugType)
        }))
        this.recommendMedicineRequestDtoList = result;
      },

      // 远程搜索推荐健康风险筛查项目
      remoteMethod (query) {
        if (query !== '') {
          let _this = this;
          _this.loading1 = true;
          this.post(this.api.promote.getRecommendPageList, {
            name: query
          }).then(res => {
            if (res.data.code === '200') {
              _this.loading1 = false;
              _this.riskList = res.data.object.map(item => ({
                healthCheckPackageId: item.id,
                name: item.name,
                type: item.healthRiskTypeName
              }));
            }
          })
          setTimeout(() => {
            _this.loading1 = false;
            _this.riskFilterList = _this.riskList.filter(item => item.name.indexOf(query) > -1);
          }, 200)
        } else {
          this.riskFilterList = [];
        }
      },
      // 选择推荐健康风险筛查项目
      handleSelect (item) {
        this.riskIds = item;
      },
      // 增加推荐健康风险筛查项目
      handleAddRisk (selVal) {
        if (selVal.length === 0) {
          this.$message.error('请选择推荐健康风险筛查项目!');
          return
        }
        let temp = this.riskList.filter(item => selVal.some(ele => ele === item.healthCheckPackageId));
        this.formModel.themeHealthDtoList = this.commonFunction.removeDuplicatedItem([...this.formModel.themeHealthDtoList, ...temp], 'healthCheckPackageId');
        this.riskIds = [];
      },
      // 删除已选健康筛查项目
      delRisk (table, index) {
        table.splice(index, 1);
      },

      // 查询详情
      getDetail () {
        this.post(this.api.promote.getComplicationInfo, {
          id: this.dataObj.id
        }).then(res => {
          if (res.data.code === '200') {
            let resData = res.data.object;
            this.deviceTargetDto = resData.deviceTargetDto.map(item => ({
              ...item,
              resultArr: item.result === '' ? [] : JSON.parse(item.result),
            }))
            resData.deviceTargetDto = this.deviceTargetDto;
            this.formModel = resData;
            // return
            // 联合荐药：
            const result = this.typeList.map(item => ({
              ...item,
              value: resData.recommendMedicineRequestDtoList.filter(sItem => item.drugType === sItem.drugType)
            }))
            this.recommendMedicineRequestDtoList = result;
            // 关联检测项
            let deviceIds = [...new Set(this.deviceTargetDto.map(item => item.deviceId))];
            let arr = [];
            deviceIds.forEach(async item => {
              const { data: result } = await this.post(this.api.promote.getReferenceInfo, { deviceId: item });
              if (result.code === '200') {
                result.object.forEach(list => {
                  arr.push(list.resultSet);
                })
                this.deviceTargetDto.forEach((el, index) => {
                  this.$set(el, 'resultSet', arr[index]);
                })
              }
            });
          }
        })
      }
    },
    created () {
      if (this.dataObj) {
        this.title = '编 辑';
        if (this.dataObj.id) {
          this.getDetail();
        } else {
          this.formModel.name = this.dataObj.name;
        }
      }
    },
    components: {
      'equipment-dialog': equipmentDialog,
      'shop-dialog': shopDialog,
      'medicine-dialog': medicineDialog,
      VueNeditorWrap
    },
    computed: {
      ...mapGetters(['fileUpload'])
    }
  }
</script>
<style scoped lang="scss">
  .w-500 {
    width: 500px;
  }
  .table-cell {
    td {
      padding: 3px 10px;
      border-bottom: 1px solid #ebeef5;
      border-right: 1px solid #ebeef5;
      &.first-td {
        border-left: 1px solid #ebeef5;
      }
    }
  }
</style>
